package com.lihaozhe.util.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lihaozhe.util.response.ResponseResult;
import com.lihaozhe.util.result.ResultCode;
import com.lihaozhe.util.string.StringUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 李昊哲
 * @version 1.0
 * @Description
 * @createTime 2021/9/3 下午12:08
 */
public class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 8428724747085777119L;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    @Override
    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        excute(req, resp);
    }

    /**
     * 执行真实方法
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    public void excute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 处理中文乱码
        // 处理post请求的中文乱码
        request.setCharacterEncoding("utf-8");
        // 处理响应的字符集中文乱码
        response.setCharacterEncoding("utf-8");
        // 处理浏览器字符集中文乱码
        response.setContentType("text/html;charset=utf-8");
        System.out.println("请求方式:" + request.getMethod());
        String methodName = request.getParameter("methodName");
        Class<? extends BaseServlet> clazz = this.getClass();
        String contentType = request.getContentType();
        try {
            if (StringUtil.isBlank(methodName)){
                printJsonObject(response,new ResponseResult(ResultCode.PARAM_ERROR.getCode(), ResultCode.PARAM_ERROR.getMsg()));
                return;
            }else {
                if (!StringUtil.isBlank(contentType) && contentType.contains("application/json")) {
                    ServletInputStream inputStream = request.getInputStream();
                    String text = IOUtils.toString(inputStream, "utf-8");
                    Method method = null;

                    method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class, String.class);

                    method.setAccessible(true);
                    method.invoke(this, request, response, text);
                } else {
                    Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                    method.setAccessible(true);
                    method.invoke(this, request, response);
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    /**
     * 向页面响应字符串
     * @param response  HttpServletResponse
     * @param Text  向页面响应的字符串
     * @throws IOException  IOException
     */
    public static void printText(HttpServletResponse response ,String Text) throws IOException {
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(Text);
        writer.flush();
        writer.close();
    }
    /**
     * 向页面响应json字符串
     * @param response  HttpServletResponse
     * @param object  向页面响应的对象
     * @throws IOException  IOException
     */
    public static void printJsonObject(HttpServletResponse response ,Object object) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(objectMapper.writeValueAsString(object));
        writer.flush();
        writer.close();
    }

    /**
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param path 请求
     * @throws ServletException
     * @throws IOException
     */
    public static void forword(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        request.getRequestDispatcher(path).forward(request,response);
    }
    public static void forwordToWEB_INF(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        forword(request,response,"/WEB-INF/" + path);
    }
    public static void forwordSuffixJSP(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        forword(request,response,path + ".jsp");
    }
    public static void forwordToWEB_INF_SuffixJSP(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        forword(request,response,"/WEB-INF/" + path  + ".jsp");
    }

    public static void redirect(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/"+ path);
    }
    public static void redirectSuffixJSP(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
        redirect(request,response,path + ".jsp");
    }

}